package com.yami.shop.common.wx;

import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import okhttp3.HttpUrl;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.util.Base64;
import java.util.Random;

public class SignUtil {
    private static final String privateKey = "-----BEGIN PRIVATE KEY-----" +
            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+Uy3gGGRQWtCB\n" +
            "DsE9Gv1Ivz8TkJaLT4pQtLyGDYDkQobjlebUBRyBcBJemdzBbpAjMKKbFOsYf7X4\n" +
            "aPnD/eiYDHM3YSLAtivtxvBub6NXturaL0ASz+s+SomogVZrElVlmOSVSvat2mOD\n" +
            "4bn3A94xSMphmtp3qwBtI7elV/xG7dw6IKKtDuMLCKPBGsstKcGXW3H9J9k9p6oj\n" +
            "PcYkbhEsdLo3TUro/MApyrXMYD5fgaMED1j1Xg4GU7G/N+NvEkUwQgt3qgG7vYq7\n" +
            "GwOpfLPkRpdtgKweOVO0Y94UtOXzNP6lmVc/sQrq3OB05oVCtCKdY7Y2KX2m1Jj7\n" +
            "BHs1jnC5AgMBAAECggEAHjeMkAivXIaele7mxTHUxsj+Vbfd/u448olPaSUZsqPR\n" +
            "UK7LABxzoyVM9VIOV3ObVMry9hZDIRedp3vbM7/LPuCzJja40snZfZ3ZLF9zGokD\n" +
            "DnL0BEiYe8JPyr4GH2fAwSmeGQnW0lFa/WRIJyypCUAaSZbRWrB+l9VU4d5vQj9Y\n" +
            "/Zi3H1AznhFQL/UM4PqW8YOorhP5pBpzRl+V1dTPSuWKb0l/Ly5qXMZioQYP+5DZ\n" +
            "5dDauiu1tt4qhmMdxSQgrUXoIJ+9acXLiv9ftorRkRTgUDaC1+jH3k4Y6y1ievC+\n" +
            "69CLshfiwLyZoOXcBesEXdS0/aIAzZr5+WnXPsfyAQKBgQD1SNjNJVqXiU+/nrH+\n" +
            "tmCQkT6UEQKC4VtRn591ONIKWQ3P7G3YzJC8dohba65jVlrT+p/Y7nVUY5tgBI1u\n" +
            "ikAsCKuHud38VQCRT3yaqmoq78BceKAkedgqyfbbW1jGgdInaVwNmQC6eWVMRkms\n" +
            "XJ0HvO6zDSsx0A5pm6jdPZa3+QKBgQDGo7AvSH1hqvvt+Bwpow+PQMC4xw1bFR4u\n" +
            "IGVN9SoVpPRgo8qxf2lxOwcfUbG1NGJWgyF+VCdLeKaeoFMC/2UiMupzvGwj311C\n" +
            "OjeGcurfEfB1b9/jhqrtP/9yDGOvPiGewaDezog9I4Osv7AW1NeYoRnimex/RSBk\n" +
            "W+SxHpcuwQKBgB+LGrZnE1thgSv3UJSdB5YP16ha96O1L3UzveHpSLmj8i7HDOlQ\n" +
            "hVx3Mdnv4yFLPar9FAllwRj1JkoWy8lnZhFDnCt8L5v/om8Ndcy+FaEn6+j4aj/G\n" +
            "m5IFHwXenXAJyejfl8L35iwU6H4Cm/7aeidAmMHV87QYOYJDTlgFT5ihAoGBALbS\n" +
            "JO//ydZAZoqJFnKD72grcrUeDv7LmvFdQ5/Six9MqNbhKUbgO43JhC6hI+vhALkb\n" +
            "C5KXpWri6oeIi55wrQYi0oIe43DIva6cokoOLnmMq0GK7AcfBOZDRroTCRRbHNpe\n" +
            "387xS5bpvuEZs9nvn1aMv6Q9gttIJh34La2OuBqBAoGAKMEBnTn6OUEsEeEvUrJB\n" +
            "4TRDMM7skkUUx6cmGudN8Kq7ePsGBlzNTrSiU2t/AstJktFzpixi0LIw396eFeTV\n" +
            "AlRDROkGesTTpOUYHpwI93vJ6Yz4Q0OWtZ8HYIVvuuYSQNDMwqOIP6Q9F4XBL99B\n" +
            "nbynwBW4MNclttjhNColyto=\n" +
            "-----END PRIVATE KEY-----";

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    public String getToken(String method, HttpUrl url, String body)  {
        String nonceStr = "your nonce string";
        try{
            long timestamp = System.currentTimeMillis() / 1000;
            String message = buildMessage(method, url, timestamp, nonceStr, body);
            String signature = sign(message.getBytes("utf-8"));
            String yourMerchantId = "";
            String yourCertificateSerialNo = "";

            return "mchid=\"" + yourMerchantId + "\","
                    + "nonce_str=\"" + nonceStr + "\","
                    + "timestamp=\"" + timestamp + "\","
                    + "serial_no=\"" + yourCertificateSerialNo + "\","
                    + "signature=\"" + signature + "\"";
        }catch (Exception e){
            e.printStackTrace();
        }
            return null;
    }

    public static String sign(byte[] message) {
        try{

            // 加载商户私钥（privateKey：私钥字符串）
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(merchantPrivateKey);//证书私钥
            sign.update(message);
            return Base64.getEncoder().encodeToString(sign.sign());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
        String canonicalUrl = url.encodedPath();
        if (url.encodedQuery() != null) {
            canonicalUrl += "?" + url.encodedQuery();
        }
        System.out.println(canonicalUrl);
        return method + "\n"
                + canonicalUrl + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + body + "\n";
    }

    public static String buildMessage2(String appId, long timestamp, String nonceStr, String prepayid) {
        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + prepayid + "\n";
    }

    /**
     * 根据pem公钥路径获取公钥字符串
     * @param cerPath 路径
    * @return 公钥字符串
    */
    public static String getPubKeyContentString(String cerPath) {
// 读取本机存放的PKCS8证书文件

        String currentPath = Thread.currentThread().getContextClassLoader().getResource(cerPath).getPath();

        try {
            //读取pem证书
            BufferedReader br = new BufferedReader(new FileReader(currentPath));
            StringBuffer publickey = new StringBuffer();
            String line;

            while (null != (line = br.readLine())) {
                if((line.contains("BEGIN PUBLIC KEY") || line.contains("END PUBLIC KEY"))){
                    continue;
                }
                publickey.append(line);

            }
            return publickey.toString();
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;

    }

    public static void main(String[] args) throws Exception {
//        HttpUrl url = HttpUrl.parse("https://api.mch.weixin.qq.com/v3/marketing/favor/users");
//        HttpUrl url = HttpUrl.parse("https://api.mch.weixin.qq.com/v3/pay/transactions/h5");
        long timestamp =  System.currentTimeMillis() / 1000;
//        String nonceStr = WXPayUtil.generateNonceStr();
//        String body = "{\n" +
//                "    \"stock_id\": \"9433645\",\n" +
//                "    \"stock_creator_mchid\": \"1605464489\",\n" +
//                "    \"out_request_no\": \"202104231840\",\n" +
//                "    \"appid\": \"wx26a2407bd5e8d5da\"\n" +
//                "}";
//        String message = buildMessage( "POST",  null, timestamp, nonceStr,body);
//        String signVal = com.java110.utils.util.SignUtil.sign(message.getBytes());
//
//        System.out.println(signVal);
//        System.out.println(timestamp);
//        System.out.println(nonceStr);

    }


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

}
